const bittrex = require('node-bittrex-api');
const gate = require('../lib/gate');
const poloniex = require('../lib/poloniex');

function contains(arr, obj) {
  var i = arr.length;
  while (i--) {
    if (arr[i] === obj) {
      return true;
    }
  }
  return false;
}

module.exports = [{
  interval: '10s',
  immediate: true,
  handle: () => {
    if (!think.allBTCTrade) {
      think.allBTCTrade = [];
    }
    if (!think.bittrexTickers) {
      think.bittrexTickers = {};
    }
    if (!think.gateTickers) {
      think.gateTickers = {};
    }
    if (!think.poloniexTickers) {
      think.poloniexTickers = {};
    }
    bittrex.options({
      'apikey': 'a',
      'apisecret': 'a'
    });

    bittrex.getmarketsummaries(function(data, err) {
      if (err) {
        return console.error(err);
      }
      for (const i in data.result) {
        const market = data.result[i].MarketName;
        bittrex.getticker({market: market}, function(ticker) {
          if (ticker && ticker.result && market.split('-')[0] === 'BTC') {
            if (!contains(think.allBTCTrade, market)) {
              think.allBTCTrade.push(market);
            }
            ticker.result.market = market;
            ticker.result.BaseVolume = data.result[i].BaseVolume;
            think.bittrexTickers[market] = ticker.result;
          }
        });
      }
    });

    gate.getTickers(function(res) {
      res = JSON.parse(res)
      for (let iKey in res) {
        const item = res[iKey];
        if (iKey.split('_')[1] === 'btc') {
          iKey = ('btc-' + iKey.split('_')[0]).toUpperCase();
          if (!contains(think.allBTCTrade, iKey)) {
            think.allBTCTrade.push(iKey);
          }
          item.market = iKey;
          think.gateTickers[iKey] = item;
        }
      }
    });

    poloniex.getTicker(function(res) {
      res = JSON.parse(res).Data;
      for (let i = 0; i < res.length; i++) {
        const iKey = 'BTC-' + res[i].Label.split('/')[0];
        if (!contains(think.allBTCTrade, iKey)) {
          think.allBTCTrade.push(iKey);
        }
        res[i].market = iKey;
        think.poloniexTickers[iKey] = res[i];
      }
    });
  }
}];
